﻿using Common;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace WebMvc.Areas.Models
{
    public partial class Model_UO_Permission
    {
        #region Method-得到用户的权限菜单 GetUserPers()
        /// <summary>
        /// 得到用户的权限菜单
        /// </summary>
        /// <returns>用户的权限菜单json字符串</returns>
        public static string GetUserPers()
        {
            string strJson = string.Empty;

            List<UO_Permission> listPers = oc.UserPermission.Where(p => p.PIsShow == true).OrderBy(p => p.POrder).ToList();

            if (listPers.Count > 0)
            {
                List<TreeNode> listTreeNodes = UO_Permission.ConvertTreeNodes(listPers, 1);
                strJson = DataHelper.ObjToJson(listTreeNodes);
            }
            return strJson;
        }

        #endregion

        #region Method-得到用户指定节点的权限菜单 GetUserPerLists(string pid)
        /// <summary>
        /// 得到用户的权限菜单
        /// </summary>
        /// <returns>用户的权限菜单json字符串</returns>
        public static string GetUserPerLists(string pid)
        {
            string strJson = string.Empty;
            int parentId = string.IsNullOrEmpty(pid) ? 0 : int.Parse(pid);

            List<UO_Permission> listPers = oc.UserPermission.Where(p => p.PIsShow == true && p.PParentID == parentId).OrderBy(p => p.POrder).ToList();

            if (listPers.Count > 0)
            {
                List<TreeNode> listTreeNodes = UO_Permission.ConvertTreeNodes(listPers, parentId);
                strJson = DataHelper.ObjToJson(listTreeNodes);
            }
            return strJson;
        }

        #endregion

        #region Method-得到所有的权限菜单的树型结构 GetAllPersForTree(bool isMemu = false, int pid = 0)
        /// <summary>
        /// 得到所有的权限菜单
        /// </summary>
        /// <returns></returns>
        public static string GetAllPersForTree(bool isMemu = false, int pid = 0)
        {
            string strJson = string.Empty;
            Expression<Func<UO_Permission, bool>> whereLambda = null;
            if (isMemu)
            {
                whereLambda = p => p.PIsShow == true;
            }
            else
            {
                whereLambda = p => p.PIsShow == false || p.PIsShow == true;
            }

            List<UO_Permission> listPers = oc.BllSession.IUO_PermissionBLL.GetListBy(
                whereLambda).OrderBy(p => p.POrder).ToList();
            if (listPers.Count > 0)
            {
                List<TreeNode> listTreeNodes = UO_Permission.ConvertTreeNodes(listPers, pid);
                strJson = DataHelper.ObjToJson(listTreeNodes);
            }

            return strJson;
        }
        #endregion

        #region Method-得到所有的权限菜单ForTreeGrid GetAllPersForTreeGrid(bool isMemu = false)
        /// <summary>
        /// 得到所有的权限菜单
        /// </summary>
        /// <returns></returns>
        public static dynamic GetAllPersForTreeGrid(bool isMemu = false)
        {

            Expression<Func<UO_Permission, bool>> whereLambda = null;
            if (isMemu)
            {
                whereLambda = p => p.PIsShow == true;
            }
            else
            {
                whereLambda = p => p.PIsShow == false || p.PIsShow == true;
            }

            List<UO_Permission> listPers = oc.BllSession.IUO_PermissionBLL.GetListBy(
                 whereLambda).OrderBy(p => p.POrder).ToList();

            List<UO_PermissionTreeGrid> listTgPers = new List<UO_PermissionTreeGrid>();

            foreach (var per in listPers)
            {
                string state = listPers.Count(p => p.PParentID == per.PParentID) == 0 ? "open" : (per.PParentID == 0 || per.PParentID == 1) ? "open" : "closed";

                UO_PermissionTreeGrid tp = new UO_PermissionTreeGrid
                {
                    _parentId = per.PParentID,
                    state = state,
                    Checked = false,
                    iconCls = per.PIcon,

                    PId = per.PId,
                    PParentID = per.PParentID,
                    PName = per.PName,
                    PAreaName = per.PAreaName,
                    PControllerName = per.PControllerName,
                    PActionName = per.PActionName,
                    PFormMethod = per.PFormMethod,
                    POperationType = per.POperationType,
                    PIcon = per.PIcon,
                    POrder = per.POrder,
                    PIsLink = per.PIsLink,
                    PLinkUrl = per.PLinkUrl,
                    PIsShow = per.PIsShow,
                    PRemark = per.PRemark,
                    PCreateTime = per.PCreateTime,
                    PUpdateTime = per.PUpdateTime
                };
                listTgPers.Add(tp);
            }

            return new DataGrid
            {
                total = listTgPers.Count(),
                rows = listTgPers,
                footer = null
            };
        }
        #endregion

        #region Method-根据用户编号得到对应的权限信息 GetUserPermission(int usrId)
        /// <summary>
        /// 根据用户编号得到对应的权限信息
        /// </summary>
        /// <param name="usrId">用户编号</param>
        /// <returns>权限集合</returns>
        public static List<UO_Permission> GetUserPermission(int usrId)
        {
            //--根据用户编号得到角色编号(集合)
            List<int> listRoleId = oc.BllSession.IUO_UserRoleBLL.Entities.Where(u => u.UId == usrId).Select(r => r.RId).ToList();
            //根据角色编号得到权限编号(集合)
            List<int> listPerIds = oc.BllSession.IUO_RolePermissionBLL.Entities.Where(rp => listRoleId.Contains(rp.RId)).Select(p => p.PId).ToList();
            //根据用户编号查询特权编号(集合)
            List<int> listVipPerIds = oc.BllSession.IUO_UserVipPermissionBLL.Entities.Where(u => u.UId == usrId).Select(vp => vp.PId).ToList();
            //把两个权限集合整到了一起
            listPerIds.ForEach(p =>
            {
                listVipPerIds.Add(p);
            });
            //根据权限编号得到权限的具体信息
            List<UO_Permission> listPers = oc.BllSession.IUO_PermissionBLL.Entities
                .Where(p => listVipPerIds.Contains(p.PId)).ToList();

            return listPers.OrderBy(u => u.POrder).ToList();
        }

        #endregion

        #region Method-判断当前用户是否有访问当前请求的权限 (string areaName, string controllerName , string actionName, HttpMethod httpmethod)
        /// <summary>
        /// 判断当前用户是否有访问当前请求的权限
        /// </summary>
        /// <param name="areaName">区域名</param>
        /// <param name="controllerName">控制制名</param>
        /// <param name="actionName">action方法名</param>
        /// <param name="httpmethod">http请求的方式</param>
        /// <returns>true：有权限 false无权限</returns>
        public static bool HasPermission(string areaName, string controllerName
            , string actionName, HttpMethod httpmethod)
        {
            var listP = from per in oc.UserPermission
                        where
                        string.Equals(per.PAreaName, areaName, StringComparison.CurrentCultureIgnoreCase)
                    && string.Equals(per.PControllerName, controllerName, StringComparison.CurrentCultureIgnoreCase)
                    && string.Equals(per.PActionName, actionName, StringComparison.CurrentCultureIgnoreCase)
                    && per.PFormMethod == (int)httpmethod
                        select per;

            return listP.Count() > 0;

        }
        #endregion

        #region Method-新增权限菜单 AddPermission(UO_Permission Permission)
        /// <summary>
        /// 新增权限菜单
        /// </summary>
        /// <param name="Permission">权限菜单</param>
        /// <returns>AjaxMsgModel实体对象</returns>
        public static AjaxMsgModel AddPermission(UO_Permission Permission)
        {
            try
            {
                int iret = oc.BllSession.IUO_PermissionBLL.Add(Permission);

                if (iret > 0)
                {
                    return new AjaxMsgModel
                    {
                        Status = AjaxStatus.ok,
                        Msg = "权限菜单新增成功！",
                        Data = null,
                        BackUrl = null
                    };
                }
                else
                {
                    return new AjaxMsgModel
                    {
                        Status = AjaxStatus.err,
                        Msg = "权限菜单新增失败！",
                        Data = null,
                        BackUrl = null
                    };
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region Method-修改权限菜单 EditPermission(UO_Permission Permission)
        /// <summary>
        /// 修改权限菜单
        /// </summary>
        /// <param name="Permission">权限菜单</param>
        /// <returns>AjaxMsgModel实体对象</returns>
        public static AjaxMsgModel EditPermission(UO_Permission Permission)
        {
            try
            {
                Expression<Func<UO_Permission, object>>[] ignoreProperties =
                        new Expression<Func<UO_Permission, object>>[] { p => p.PId, p => p.PCreateTime, p => p.ButtonList, p => p.Check, p => p.UO_RolePermission, p => p.UO_UserVipPermission };

                int iret = oc.BllSession.IUO_PermissionBLL.Modify(Permission, ignoreProperties);

                if (iret > 0)
                {
                    return new AjaxMsgModel
                    {
                        Status = AjaxStatus.ok,
                        Msg = "权限菜单修改成功！",
                        Data = null,
                        BackUrl = null
                    };
                }
                else
                {
                    return new AjaxMsgModel
                    {
                        Status = AjaxStatus.err,
                        Msg = "权限菜单修改失败！",
                        Data = null,
                        BackUrl = null
                    };
                }
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
        }
        #endregion

        #region Method-删除权限菜单 DelPermission(int pId)
        /// <summary>
        /// 删除权限菜单
        /// </summary>
        /// <param name="pId">要删除的权限菜单编号</param>
        /// <returns>AjaxMsgModel实体对象</returns>
        public static AjaxMsgModel DelPermission(int pId)
        {
            int pCount = oc.BllSession.IUO_PermissionBLL.Entities.Count(u => u.PParentID == pId);
            if (pCount > 0)
            {
                return new AjaxMsgModel
                {
                    Status = AjaxStatus.err,
                    Msg = "此权限菜单有子菜单，不允许直接删除！",
                    Data = null,
                    BackUrl = null
                };
            }


            int uCount = oc.BllSession.IUO_RolePermissionBLL.Entities.Count(u => u.PId == pId);
            if (uCount > 0)
            {
                return new AjaxMsgModel
                {
                    Status = AjaxStatus.err,
                    Msg = "此权限菜单已被角色使用，不允许直接删除！",
                    Data = null,
                    BackUrl = null
                };
            }

            int rCount = oc.BllSession.IUO_UserVipPermissionBLL.Entities.Count(u => u.PId == pId);
            if (rCount > 0)
            {
                return new AjaxMsgModel
                {
                    Status = AjaxStatus.err,
                    Msg = "此权限菜单已关联用户，不允许直接删除！",
                    Data = null,
                    BackUrl = null
                };
            }

            int iret = oc.BllSession.IUO_PermissionBLL.DelBy(p => p.PId == pId);
            if (iret > 0)
            {
                return new AjaxMsgModel
                {
                    Status = AjaxStatus.ok,
                    Msg = "权限菜单删除成功！",
                    Data = null,
                    BackUrl = null
                };
            }
            else
            {
                return new AjaxMsgModel
                {
                    Status = AjaxStatus.err,
                    Msg = "权限菜单删除失败！",
                    Data = null,
                    BackUrl = null
                };
            }

        }
        #endregion
    }
}